;
(function ($) {
    /*
     * 说明：获取浏览器前缀
     * 实现：判断某个元素的css 样式中是否存在transition属性
     * 参数：dom元素
     * 返回值：boolean ，有则返回浏览器样式前缀，否则返回false
     * */
    var _prefix = (function (temp) {
        var aPrefix = ['webkit', 'Moz', 'o', 'ms'],
            props = '';
        for (var i in aPrefix) {
            props = aPrefix[i] + 'Transition';
            if (temp.style[props] !== undefined) {
                return '-' + aPrefix[i].toLowerCase() + '-';
            }
        }
        return false;
    })(document.createElement(PageSwitch));

    var PageSwitch = (function () {
        function PageSwitch(element, options) {
            this.settings = $.extend(true, $.fn.PageSwitch.defaults, options || {});
            this.element = element;
            this.init();
        }

        PageSwitch.prototype = {
            /*
             * 说明：初始化插件
             * 实现：初始化dom结构，布局，分页及绑定事件
             * */
            init: function () {
                var self = this;
                self.selectors = self.settings.selectors;
                self.sections = self.element.find(self.selectors.sections);
                self.section = self.element.find(self.selectors.section);

                self.canScoll = true;

                self.direction = (self.settings.direction == 'vertical' ? true : false);
                self.pagesCount = self.pagesCount();

                self.index = (self.settings.index >= 0 && self.settings.index < self.pagesCount) ? self.settings.index : 0;

                if (!self.direction) self._initLayout(); //如果横屏，初始化页面
                if (self.settings.pagination) self._initPaging();
                self._initEvent();

            },
            /*说明：获取滑动页面数量*/
            pagesCount: function () {
                return this.section.length;
            },
            /*说明：获取滑动的宽度（横屏滑动）或高度（竖屏滑动）*/
            switchLength: function () {
                return this.direction ? this.element.height() : this.element.width();
            },
            /*说明：向前滑动即上一页面*/
            prev: function () {
                var self = this;
                if (self.index > 0) {
                    self.index--;
                } else if (self.settings.loop) {
                    self.index = self.pagesCount - 1;
                }

                self._scrollPage();
            },
            /*说明：向后滑动即下一页面*/
            next: function () {
                var self = this;
                if (self.index < self.pagesCount - 1) {
                    self.index++;
                } else if (self.settings.loop) {
                    self.index = 0;
                }
                self._scrollPage();
            },
            /*说明：主要针对横屏情况进行页面布局*/
            _initLayout: function () {
                var self = this,
                    width = (self.pagesCount * 100) + '%',
                    cellWidth = (100 / self.pagesCount).toFixed(2) + '%';
                self.sections.width(width);
                self.section.width(cellWidth).css('float', 'left');
            },
            /*说明：实现分页的dom结构及css样式*/
            _initPaging: function () {
                var self = this,
                    pagesClass = self.selectors.page.substring(1),
                    pageHtml = '<ul class="' + pagesClass + '">',
                    i = 0;
                self.activeClass = self.selectors.active.substring(1);
                for (; i < self.pagesCount; i++) {
                    pageHtml += '<li></li>';
                }
                pageHtml += '</ul>';
                self.element.append(pageHtml);

                var pages = self.element.find(self.selectors.page);
                self.pageItem = pages.find('li');

                self.pageItem.eq(self.index).addClass(self.activeClass);

                if (self.direction) {
                    pages.addClass('vertical');
                } else {
                    pages.addClass('horizontal');
                }

                //pages.addClass( self.direction ? 'vertical' : 'horizontal' );
            },
            /*说明：初始化插件事件*/
            _initEvent: function () {
                var self = this;
                self.element.on('click', self.selectors.page + ' li', function () {
                    self.index = $(this).index();
                    self._scrollPage();
                });
                self.element.on('mousewheel DOMMouseScroll', function (e) {
                    if (self.canScoll) {
                        var delta = e.originalEvent.wheelDelta || -e.originalEvent.detail;//判断滚轮的方向事件，大于0 向上滚动，小于0 向下滚动
                        if (delta > 0 && (self.index && !self.settings.loop || self.settings.loop)) {
                            self.prev();
                        } else if (delta < 0 && (self.index < (self.pagesCount - 1) && !self.settings.loop || self.settings.loop )) {
                            self.next();
                        }
                    }
                });
                if (self.settings.keyboard) {
                    $(window).on('keydown', function (e) {
                        var keyCode = e.keyCode;
                        if (keyCode == 37 || keyCode == 38) {
                            self.prev();
                        } else if (keyCode == 39 || keyCode == 40) {
                            self.next();
                        }
                    });
                }
                $(window).resize(function () {
                    var currentLength = self.switchLength(),
                        offset = self.settings.direction ? self.section.eq(self.index).offset().top :
                            self.section.eq(self.index).offset().left;
                    if (Math.abs(offset) > currentLength / 2 && self.index < (self.pagesCount - 1)) self.index++;
                    if (self.index) self._scrollPage();
                });
                /*css 的transition动画完成后触发该事件，兼容各浏览器*/
                self.sections.on('transitionend webkitTransitionEnd oTransitionEnd otransitionend', function () {
                    self.canScoll = true;
                    if (self.settings.callback && $.type(self.settings.callback) == 'function')

                        self.settings.callback(self.index);     //传递参数，当前页数
                });
            },
            /*说明：页面滑动动画*/
            _scrollPage: function () {
                var self = this,
                    dest = self.section.eq(self.index).position();
                if (!dest) return;
                self.canScoll = false;
                if (_prefix) {
                    self.sections.css(_prefix + 'transition', 'all ' + self.settings.duration + 'ms ' + self.settings.easing);
                    var translate = self.direction ? 'translateY(-' + dest.top + 'px)' : 'translateX(-' + dest.left + 'px)';
                    self.sections.css(_prefix + 'transform', translate);
                } else {
                    var animateCss = self.direction ? {top: -dest.top} : {left: -dest.left};
                    self.sections.animate(animateCss, self.settings.duration, function () {
                        self.canScoll = true;
                        if (self.settings.callback && $.type(self.settings.callback) == 'function')
                            self.settings.callback(self.index);      //传递参数，当前页数
                    });
                }
                if (self.settings.pagination)
                    self.pageItem.eq(self.index).addClass(self.activeClass).siblings('li').removeClass(self.activeClass);
            }
        };
        return PageSwitch;
    })();

    $.fn.PageSwitch = function (options) {
        return this.each(function () {
            var $this = $(this),
                instance = $this.data('PageSwitch');
            if (!instance) {
                instance = new PageSwitch($this, options);
                $this.data('PageSwitch', instance);
            }
            if ($.type(options) === 'string') return instance[options]();
        });
    };
    $.fn.PageSwitch.defaults = {
        selectors: {    //存放插件的基本元素
            sections: '.sections',
            section: '.section',
            page: '.pages',
            active: '.active'
        },
        index: 0,                  //页面开始的索引,默认从第一页开始
        easing: 'ease',           //动画效果    ease：（逐渐变慢）默认值; linear：（匀速） ease-in：(加速) ease-out：（减速） ease-in-out（加速然后减速）
        duration: 500,             //动画执行时间
        loop: false,                //是否允许循环播放
        pagination: true,          //是否显示分页控件
        keyboard: true,             //是否支持键盘事件
        direction: 'vertical',     //滑动方向，vertical , horizontal
        callback: null              //回调函数
    };
    /*$(function () {
     $('[data-PageSwitch]').PageSwitch();
     });*/

})(jQuery);
